package com.flycent.hqhs.ui;

import java.lang.ref.WeakReference;
import java.util.List;

import net.tsz.afinal.FinalActivity;
import net.tsz.afinal.annotation.view.ViewInject;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.TextView;

import com.flycent.hqhs.App;
import com.flycent.hqhs.R;
import com.flycent.hqhs.bean.BrandRecommend;
import com.flycent.hqhs.bean.PageEntity;
import com.flycent.hqhs.bean.ProductCategory;
import com.flycent.hqhs.http.WebClient;
import com.flycent.hqhs.http.WebException;
import com.flycent.hqhs.ui.view.AbsViewHolderAdapter;
import com.flycent.hqhs.ui.view.RefreshViewLoadMoreProxy;
import com.flycent.hqhs.ui.view.RefreshViewLoadMoreProxy.OnLoadDataActionListener;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshGridView;
import com.nostra13.universalimageloader.core.ImageLoader;

/**
 * @author fbl
 *  品牌推荐
 */
public class BrandRecommendActivity extends BackableTitleBarActivity implements OnLoadDataActionListener{
	@ViewInject(id = R.id.barend_recommend_loading_text ) TextView mLoadingText;
	@ViewInject(id = R.id.brand_radioGroup ) RadioGroup mGroup;

	PullToRefreshGridView mRefreshGridView;
	RefreshViewLoadMoreProxy mLoadMoreProxy;
	private List<BrandRecommend> mBrandRecommends;
	private BrandRecommendAdapter mAdapter;
	private int nowpage = 1;
	private List<ProductCategory> mpCategories;	
	private int selectId = 0;  
	private int productCategoryId ;
	private boolean isFirst = true;
	private boolean istrue = true;
	private Handler mHandler = new MyHandler(this);

	@Override
	protected void onCreate(Bundle savedInstance) {
		super.onCreate(savedInstance);
		setContentView(R.layout.activity_brand_recommend);
		FinalActivity.initInjectedView(this);
		getTitleBar().setTitle("品牌推荐");
		//获取分类
		getcategory();
		//radiogroup切换
		mGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			@Override
			public void onCheckedChanged(RadioGroup group, int checkId) {
				productCategoryId = checkId;
				if(isFirst){
					dogetlist();
					isFirst = false;
				}else {
					onRefresh(1);
					canClick(false);
				}
			}
		});

	}

	private void getcategory() {
		showLoadingDialog("");
		new Thread(){
			public void run() {
				try {
					mpCategories = WebClient.getInstance(BrandRecommendActivity.this).productCategorys();
					mHandler.sendEmptyMessage(2);
				} catch (WebException e) {
					dismissLoadingDialog();
					e.printStackTrace();
				}catch (Exception e) {
					dismissLoadingDialog();
				}
			};
		}.start();

	}

	@Override
	public void onRefresh(int page) {
		updateBrandList(1, true);
	}
	@Override
	public void onLoadMore(int page) {
		nowpage++;
		updateBrandList(nowpage, false);

	}
	//请求列表
	private void updateBrandList(final int pageNum,final boolean isRefresh){
		//		mLoadMoreProxy.loadDataActionComplete(false);

		new Thread(){
			public void run() {
				WebClient client = WebClient.getInstance(BrandRecommendActivity.this);
				try {

					PageEntity<BrandRecommend> entity = client.getBandRecommend(productCategoryId+"",pageNum, 20, "", "asc");

					int totlePage = entity.getTotalPages();
					mBrandRecommends = entity.getContent();
					if(pageNum > totlePage){
						App.showShortToast(R.string.the_end_page);
						mBrandRecommends = null;
					}
				} catch (WebException e) {
					if (WebException.TYPE_SERVER_RETURN_NULL.equals(e.getStatusCode())){
						mBrandRecommends = null;
					}else
						e.printStackTrace();
				}

				if(isRefresh)
					mHandler.sendEmptyMessage(0);	
				else
					mHandler.sendEmptyMessage(1);
			};
		}.start();

		//		mLoadMoreProxy.loadDataActionComplete(true);
	}

	@SuppressLint("HandlerLeak") 
	private class MyHandler extends Handler{

		private WeakReference<Activity> mActivity;

		private MyHandler(Activity activity){
			mActivity = new WeakReference<Activity>(activity);
		} 

		@Override
		public void dispatchMessage(Message msg) {
			super.dispatchMessage(msg);
			if( mActivity.get() != null ){
				switch (msg.what) {
				case 0:
					canClick(true);
					mAdapter.update(mBrandRecommends);
					mRefreshGridView.onRefreshComplete();
					break;
				case 1:
					canClick(true);
					mAdapter.append(mBrandRecommends);
					mRefreshGridView.onRefreshComplete();
					break;
				case 2:
					dismissLoadingDialog();
					setTitleCategroy();
					break;

				default:
					break;
				}

			}
		}
	}

	//动态加radiobutton
	private void setTitleCategroy() {
		for (int i = 0; i < mpCategories.size(); i++) {
			RadioButton radio = new RadioButton(BrandRecommendActivity.this); 
			radio = (RadioButton) LayoutInflater.from(BrandRecommendActivity.this).inflate(R.layout.item_radiobuttom, null);
			radio.setLayoutParams(new RadioGroup.LayoutParams(  
					RadioGroup.LayoutParams.WRAP_CONTENT,  
					RadioGroup.LayoutParams.WRAP_CONTENT));  
			radio.setText(mpCategories.get(i).getName());
			int mid = Integer.parseInt(mpCategories.get(i).getId()+"");
			radio.setId(mid);  
			if ("mid".equals(mGroup.getCheckedRadioButtonId())) {  
				selectId = mid;  
			}  
			if(i == 0 ){
				selectId = mid;
			}
			mGroup.addView(radio);  
		}  
		mGroup.check(selectId);   //根据这个来设置默认选中的项  

	};

	private void dogetlist() {
		mRefreshGridView = (PullToRefreshGridView) findViewById(R.id.barend_recommend_list);
		mRefreshGridView.getRefreshableView().setSelector(new ColorDrawable(Color.TRANSPARENT));

		mAdapter = new BrandRecommendAdapter(BrandRecommendActivity.this, R.layout.item_brand_recommend);
		mRefreshGridView.setAdapter(mAdapter);
		mLoadMoreProxy = new RefreshViewLoadMoreProxy(mRefreshGridView, Mode.BOTH,0,0);
		mLoadMoreProxy.setOnLoadDataActionListener(this);
		mLoadMoreProxy.refreshing();

		mRefreshGridView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position,
					long id) {
				BrandRecommend mr= mAdapter.getData().get(position);
				Intent intent = new Intent(BrandRecommendActivity.this,BrandListActivity.class);
				intent.putExtra("brandId", mr.getId()+"");
				intent.putExtra("brandName", mr.getName());
				intent.putExtra("productCategoryId", productCategoryId);
				startActivity(intent);

			}

		});

	}

	public class BrandRecommendAdapter extends AbsViewHolderAdapter<BrandRecommend>{

		public BrandRecommendAdapter(Context context, int layoutRes) {
			super(context, layoutRes);
		}

		@Override
		protected void bindData(int pos, final BrandRecommend itemData) {
			ImageView mImg = getViewFromHolder(R.id.item_brand_image);
			ImageView mImg1 = getViewFromHolder(R.id.item_brand_image1);

			ImageLoader.getInstance().displayImage(itemData.getProductDTO().getImage(), mImg);
			ImageLoader.getInstance().displayImage(itemData.getImage(), mImg1);

		}
	}

	public void canClick(boolean b){
		if(b){
			mLoadingText.setVisibility(View.GONE);
		}else {
			if(istrue ){
				mLoadingText.setVisibility(View.GONE);
				istrue = false;
			}else {
				mLoadingText.setVisibility(View.VISIBLE);
			}
		}
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		mHandler.removeCallbacksAndMessages(null);
	}


}
